package com.yonyou.pmclouds.workflow.service;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.workflow.entity.ProcessDefinitionVO;
import com.yonyou.pmclouds.workflow.entity.ProcessTaskVO;
import com.yonyou.pmclouds.workflow.util.WorkFlowConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import yonyou.bpm.rest.TaskService;
import yonyou.bpm.rest.exception.RestException;
import yonyou.bpm.rest.request.task.TaskQueryParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ProcessTaskClientService {

    private final ProcessClientService processService;

    public static ObjectMapper mapper = new ObjectMapper();

    static {
        // 转换为格式化的json
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // 如果json中有新增的字段并且是实体类类中不存在的，不报错
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Autowired
    public ProcessTaskClientService(ProcessClientService processService) {
        this.processService = processService;
    }

    public TaskService getDefaultTaskService() throws BusinessException {
        TaskService taskService = processService.getDefaultTaskService(RuntimeEnvironment.getLoginUserId(), RuntimeEnvironment.getTenantId());
        return taskService;
    }

    /**
     * 查询流程待办信息
     * @param param
     * @return
     * @throws BusinessException
     */
    public ProcessTaskVO[] queryProcessTaskVOs(TaskQueryParam param) throws BusinessException{
        JsonNode jsonNode;
        try {
            Object resultObj = getDefaultTaskService().queryTasks(param);
            if(resultObj == null)
                throw new BusinessException(WorkFlowConst.YS_NULL_RESP_MSG);
            jsonNode = (JsonNode) resultObj;
        } catch (RestException e) {
            log.error(e.getMessage(),e);
            throw new BusinessException("查询流程待办信息失败：" + e.getMessage());
        }
        JsonNode data = jsonNode.get("data");
        List<ProcessTaskVO> processTaskVOList = new ArrayList<ProcessTaskVO>();
        for (JsonNode taskInfo : data) {
            ProcessTaskVO processTaskVO = new ProcessTaskVO();
            processTaskVO.setPkReceiver(taskInfo.get("assignee").textValue());
            processTaskVO.setTaskId(taskInfo.get("id").textValue());
            processTaskVO.setProcessInstanceId(taskInfo.get("processInstanceId").textValue());

            processTaskVOList.add(processTaskVO);
        }
        if(processTaskVOList.size() == 0)
            return new ProcessTaskVO[0];
        return processTaskVOList.toArray(new ProcessTaskVO[0]);
    }

    /**
     * 指派检查，assignAble为true，则可指派
     * @param taskId 任务ID
     * @return 指派检查结果
     */
    public Map<String, Object> assignCheck(String taskId, ProcessDefinitionVO definitionVO, SuperVO businessVO) throws BusinessException{
        try {
            JsonNode jsonNode = (JsonNode) getDefaultTaskService().assignCheck(taskId);
            if(jsonNode == null) {
                throw new BusinessException(WorkFlowConst.YS_NULL_RESP_MSG);
            }
            return processService.getAssignInfo(jsonNode, definitionVO, businessVO);
        }catch (RestException e){
            throw new BusinessException("指派检查失败 : " + e.getMessage());
        }
    }

    public ProcessDefinitionVO getDefinitionVOByType(String billType, SuperVO businessVO) throws BusinessException{
        return processService.getDefinitionByType(billType, businessVO);
    }
}
